//
//  UserModel.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/3.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire



enum FlagType: String {
    case findbackpwd    //找回密码
    case agentapply     //代理
    case register = ""  //注册
}
//认证状态
enum CertificationStatus: Int {
    case beReturn = -2      //被退回
    case uncertified = 0   //没有认证
    case certificationInProgress       //认证中
    case authenticated //已认证
    case openAccount    //待开户
    case unKnow     //未知，可能没有登录
}

class UserModel: NSObject {
    var accountId: String?
    var userKey: String?
    var companyId: String?
    var certificationStatus: CertificationStatus? //认证状态

    init(_ entityDic: [String: AnyObject]) {
        if let key = entityDic["Key"] {
            self.userKey = key as? String
        }
        
        if let accountId = entityDic["AccountId"] {
            self.accountId = accountId as? String
        }
        
        if let companyId = entityDic["CompanyID"] {
            self.companyId = companyId as? String
        }
        
        if let status = entityDic["CertificationStatus"] as? String {
            let statusInt = Int(status)
            self.certificationStatus = CertificationStatus(rawValue: statusInt ?? 0)
        }
    }
}

extension UserModel {
    
    //登录第一步
    class func login (username: String, password: String, completionHandler: @escaping (WWValueResponse<String>) -> Void) {
        guard let registerId = JPUSHService.registrationID() else {
            return
        }
        guard let deviceUDID = LoginAuthenticationService.getUDIDWithKeychain(jpushID: registerId) else {
            return
        }
        print(deviceUDID)
        let params = ["loginName":username, "password":password, "companyType": "建筑工人","deviceID":deviceUDID]
        let actionUrl = "http://app.winshe.cn/UserLoginForAppNew"
        let actionHeader = "UserLoginForAppNew"
        ReqWebService.reqWebService(WebServiceURL + "?op=UserLoginForAppNew", action: actionUrl,actionHeader:actionHeader, params: params){ (response) in
            
            if response.success {
                let dic = response.value as! [String: AnyObject]
                
                let aStatus = StatusStruct(rootJson: dic)
    
                if aStatus.success {
                    let userModel = UserModel.init(dic)
                    WWUser.sharedInstance.userModel = userModel
                    let accountId = dic["AccountId"] as! String
                    let key = dic["Key"] as! String
                    LoginAuthenticationService.save(username: username, password: password)
                    
                    login(accountId: accountId, key: key, completionHandler: completionHandler)
                    return
                }
                if aStatus.statusString == "MultiUserLoginError"{
            completionHandler(WWValueResponse.init(success: false, message: "MultiUserLoginError"))
                   return
                }
                
            completionHandler(WWValueResponse.init(success: aStatus.success, message: aStatus.statusString))
                return
            }
            completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
        }

    }
    
    
    
    class func multiUserErrorlogin (username: String, password: String, completionHandler: @escaping (WWValueResponse<String>) -> Void) {
        guard let registerId = JPUSHService.registrationID() else {
            return
        }
        let params = ["loginName":username, "password":password, "companyType": "建筑工人"]
        let actionUrl = "http://app.winshe.cn/UserLoginForAppNew"
        let actionHeader = "UserLoginForAppNew"
        ReqWebService.reqWebService(WebServiceURL + "?op=UserLoginForAppNew", action: actionUrl,actionHeader:actionHeader, params: params){ (response) in
            
            if response.success {
                let dic = response.value as! [String: AnyObject]
                
                let aStatus = StatusStruct(rootJson: dic)
               
                if aStatus.success {
                    let userModel = UserModel.init(dic)
                    WWUser.sharedInstance.userModel = userModel
                    let accountId = dic["AccountId"] as! String
                    let key = dic["Key"] as! String
                    LoginAuthenticationService.save(username: username, password: password)
                    
                    login(accountId: accountId, key: key, completionHandler: completionHandler)
                    return
                }
                if aStatus.statusString == "MultiUserLoginError"{
                    completionHandler(WWValueResponse.init(success: false, message: "MultiUserLoginError"))
                    return
                }
                
                completionHandler(WWValueResponse.init(success: aStatus.success, message: aStatus.statusString))
                return
            }
            completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
        }
        
    }
    
    
    
    
    
    
    //登录第二步
    class func login(accountId: String, key: String, completionHandler: @escaping (WWValueResponse<String>) -> Void) {
        let params = ["accountId":accountId, "key": key]
        
        let actionUrl = "http://app.winshe.cn/GetWebApiInfoWithKey"
        let actionHeader = "GetWebApiInfoWithKey"
        ReqWebService.reqWebService(WebServiceURL, action: actionUrl, actionHeader: actionHeader, params: params) { (response) in
            if response.success {
                let dic = response.value as! [String: AnyObject]
                
                let status = StatusStruct(rootJson: dic)
                if status.success {
                    let token = dic["Token"] as! String
                    WWUser.sharedInstance.token = token
                }
                
              completionHandler(WWValueResponse.init(success: status.success, message: status.statusString))
                
                return
            }
            
        completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
            
        }
    }
    class func multiUserlogin(accountId: String, key: String, completionHandler: @escaping (WWValueResponse<String>) -> Void) {
        let params = ["accountId":accountId, "key": key]
        
        let actionUrl = "http://app.winshe.cn/GetWebApiInfoWithKey"
        let actionHeader = "GetWebApiInfoWithKey"
        ReqWebService.reqWebService(WebServiceURL, action: actionUrl, actionHeader: actionHeader, params: params) { (response) in
            if response.success {
                let dic = response.value as! [String: AnyObject]
                
                let status = StatusStruct(rootJson: dic)
                if status.success {
                    let token = dic["Token"] as! String
                    WWUser.sharedInstance.token = token
                }
                
             completionHandler(WWValueResponse.init(success: false, message: "MultiUserLoginError"))
                return
            }
            
            completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
            
        }
    }
    
    
    
    
    
    
    
    
    
    /// 获取验证码
    class func requestSecurityCode(phoneNumber: String,flag: FlagType, completionHandler: @escaping (WWValueResponse<String?>) -> Void) {
        let flag = flag.rawValue
        let parames = ["phoneNumber" : phoneNumber, "flag": flag]
        let actionUrl = "http://app.winshe.cn/GetSMSVerificationWithFlag"
        let actionHeader = "GetSMSVerificationWithFlag"
        ReqWebService.reqWebService(WebServiceURL + "?op=GetSMSVerificationWithFlag", action: actionUrl, actionHeader: actionHeader, params: parames) { (response) in
            if response.success {
                if let dict = response.value as? [String: AnyObject] {
                    let statusString = dict["Status"] as? String
               completionHandler(WWValueResponse.init(value: statusString, success: true))
                    return
                }
                completionHandler(WWValueResponse.init(success: false, message: "数据解析出错"))
            }
            else {
             completionHandler(WWValueResponse.init(success: false, message: "网络访问出错"))
            }
            
        }
    }
    
    /// 校验验证码
    class func checkVerification(_ phoneNumber: String, verificaitonCode: String, flag:FlagType, completionHandler: @escaping (WWResponse) -> Void) {
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else  {
            return
        }
        
        guard let accountId = WWUser.sharedInstance.accountId else {
            return
        }
        
        let method = "MarTian.WebSitePortal.Handler.AjaxSignUp.CheckVerificationCode"
        let flag = flag.rawValue
        let params = ["Method": method, "phoneNumber":phoneNumber, "VerificationCode":verificaitonCode, "flag": flag, "AccountId": accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["State"] as? String, status == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        let err = dict["Err"] as? String
                        completionHandler(WWResponse.init(success: false, message: err))
                    }
                    return
                }
                completionHandler(WWResponse.init(success: false, message: "数据解析错误"))
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "网络访问错误！"))
                
            }
        }
    }
    
    /// 注册
    class func register(phoneNumber: String, verification: String, password: String, completionHandler: @escaping (WWResponse) -> Void) {
        let interval = Int(Date().timeIntervalSince1970 * 1000)
        let intervalString = "\(interval)"
        
        let username = "jzg" + intervalString
        let companyName = "jzg" + intervalString
        let accountId = "jzg" + intervalString
        let companyType = "建筑工人"
        let password = password
        let verification = verification
        
        let actionUrl = "http://app.winshe.cn/SignUp"
        let actionHeader = "SignUp"
        
        let params = ["userName": username, "accountId":accountId, "passWork": password, "cellPhoneNumber": phoneNumber, "companyType": companyType, "companyName": companyName, "verification": verification]
        
        ReqWebService.reqWebService(WebServiceURL + "?op=SignUp", action: actionUrl, actionHeader: actionHeader, params: params) { (response) in
            if response.success {
                if let dict = response.value as? [String: AnyObject] {
                    let status = StatusStruct(rootJson: dict)
                    if status.success {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        let errorMessage = dict["Status"] as? String
                        completionHandler(WWResponse.init(success: false, message: errorMessage))
                    }
                    return
                }
              
                completionHandler(WWResponse.init(success: false, message: "数据有错误"))
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "网络错误"))
            }
            
        }
        
    }
    
    /// 找回密码
    class func findPassword(phoneNumber: String, verificationCode: String,password: String,  completionHandler: @escaping (WWResponse) -> Void) {
        let actionUrl = "http://app.winshe.cn/FindBackPwdForApp"
        let actionHeader = "FindBackPwdForApp"
        
        let params = ["phoneNumber": phoneNumber, "verifycode": verificationCode, "companyType":"建筑工人", "password":password]
        ReqWebService.reqWebService(WebServiceURL + "?op=FindBackPwdForApp", action: actionUrl, actionHeader: actionHeader, params: params) { (response) in
            if response.success {
                if let dict = response.value as? [String: AnyObject] {
                    if let statusString = dict["Status"] as? String {
                        if statusString == "OK" {
                            completionHandler(WWResponse.init(success: true))
                        }
                        else {
                            let result = dict["Result"] as! String
                            completionHandler(WWResponse.init(success: false, message: result))
                        }
                        return
                    }
                }
                completionHandler(WWResponse.init(success: false, message: "数据解析出错"))
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "网络错误"))
            }
            
        }
    }
    
    //修改密码
    class func modifyPassword(_ oldPassword: String, newPassword: String, completionHandler:@escaping (WWResponse) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let userModel = WWUser.sharedInstance.userModel, let accountId = userModel.accountId else {
           
            return
        }
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        let method = "KouFine.Handler.Core.AjaxOther.ModifyPassword"
        
        let params = ["Method": method, "rawPwd": oldPassword, "pwd":newPassword, "AccountId":accountId]
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let value = response.result.value{
                    if value == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        completionHandler(WWResponse.init(success: false, message: value))
                    }
                    return
                }
                completionHandler(WWResponse.init(success: false, message: "数据解析错误"))
            }
            else {
                
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }

    }
    
    /// 手机号申诉验证
    class func checkPhoneNumber(_ oldPhoneNumber: String, currentPhoneNumber: String, verifyCode: String, completionHandler:@escaping (WWResponse) -> Void) {
        let params = ["oldphoneNumber": oldPhoneNumber, "phoneNumber": currentPhoneNumber, "verifycode": verifyCode]
        
        let actionUrl = "http://app.winshe.cn/CheckMGAppealPhone"
        let actionHeader = "CheckMGAppealPhone"
        ReqWebService.reqWebService(WebServiceURL + "?op=CheckMGAppealPhone", action: actionUrl, actionHeader: actionHeader, params: params) { (response) in
            if response.success {
                if let dict = response.value as? [String: AnyObject] {
                    let status = dict["Status"] as? String
                    if status == "OK" {
                        let userModel = UserModel.init(dict)
                        WWUser.sharedInstance.userModel = userModel
                        let accountId = dict["AccountId"] as! String
                        let key = dict["Key"] as! String
                        login(accountId: accountId, key: key, completionHandler: completionHandler)
                        return
                    }
                    
                    if status == "ERROR" {
                        let result = dict["Result"] as? String
                    completionHandler(WWResponse.init(success: false, message: result))
                        return
                    }
                }
                completionHandler(WWResponse.init(success: false, message: "未知错误"))
            }
            else {
                completionHandler(WWResponse.init(success: false, message: "网络访问错误"))
            }
        }
    }
    
    //获取guid，单个
    class func getGuid (completionHandler: @escaping (WWValueResponse<String>) -> Void) {
        guard let model = WWUser.sharedInstance.userModel else {
            return
        }
        let accountId = model.accountId
        let params = ["Method":"MarTian.BasicHandler.AjaxCommonApp.GetNewGuid","AccountId":accountId!]
        let headerDic = ["Authorization": "Bearer" + " " + WWUser.sharedInstance.token!]
        Alamofire.request(LC_DetailUrl, method: .post, parameters: params, headers:headerDic ).responseJSON { (response) in
            if response.result.isSuccess {
                let dic = response.result.value as! [String: AnyObject]
                let status = StatusStruct(rootJson: dic)
            
                if status.success {
                    let guid = dic["Guid"] as! String
                    completionHandler(WWValueResponse.init(value: guid, success: true))
                }
                else {
                    completionHandler(WWValueResponse.init(success: false, message: status.statusString))
                }
            }
            else {
                completionHandler(WWValueResponse.init(success: false, message: "网络错误！"))
            }
        }
    }
    
    //获取guid，多个
    class func getGuidList (_ number: Int,completionHandler: @escaping (WWValueResponse<[String]>) -> Void) {
        guard let model = WWUser.sharedInstance.userModel else {
            return
        }
        let accountId = model.accountId
        let params = ["Method":"MarTian.BasicHandler.AjaxCommonApp.GetNewGuid", "number":"\(number)","AccountId":accountId!]
        let headerDic = ["Authorization": "Bearer" + " " + WWUser.sharedInstance.token!]
        Alamofire.request(LC_DetailUrl, method: .post, parameters: params, headers:headerDic ).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    if let status = dict["Status"] as? String {
                        if status == "OK" {
                            if let callbackArr = dict["Guid"] as? [String] {
                    completionHandler(WWValueResponse.init(value: callbackArr, success: true))
                                return
                            }
                            
                        }
                    }
                }
                completionHandler(WWValueResponse.init(success: false, message: "获取guid出错"))

            }
            else {
                completionHandler(WWValueResponse.init(success: false, message: "网络错误！"))
            }
        }
    }

    
    
    /// 获取orderNo
    ///
    /// 表示表单编号
    /// - Parameters:
    ///   - orderConfigId: 对应表单的orderConfigId,一般是固定的一个
    class func getOrderNo(orderConfigId: String, completionHandler:@escaping (WWValueResponse<String>) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        guard let httpHeader = mobile_cilent_headers() else {
            return
        }
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId else {
            return
        }
        
        let method = "MarTian.BasicHandler.AjaxCommonApp.GetAutoNumber"
        
        let params = ["Method": method, "orderConfigId":orderConfigId, "AccountId": accountId]
        
        Alamofire.request(url, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                let value = response.result.value as! [String: AnyObject]
                let status = StatusStruct(rootJson: value)
                if status.success {
                    guard let orderNo = value["OrderNo"] as? String else {
                        
                        return
                    }
                    completionHandler(WWValueResponse.init(value: orderNo, success: true))
                    return
                }
                completionHandler(WWValueResponse.init(success: false, message: status.statusString ?? ""))
            }
            else {
               
         completionHandler(WWValueResponse.init(success: false, message: "获取orderConfigId出错"))
            }
        }
    }
    
}

enum Sex: Int {
    case boy = 0, girl
}
class UserInfoModel {
    var cellPoneNumber: String? //手机号
    var idCard: String? //身份证号
    var username: String?   //用户名
    var photoUrl: String? //认证资料头像地址
    var avatarUrl: String? //个人信息头像地址（『我』界面）
    var sex: Sex? //性别
    var province: String? //所在省
    var provinceModel: ProviceModel?
    var city: String? //所在市
    var cityModel: CityModel?
    var positiveIdCardUrl: String? //正面身份证地址
    var reverseIdCardUrl: String? //反面身份证地址
    var address:String?
    var iDCardValidEndDate:String?
    var iDCardValidBeginDate:String?
    
    required init(_ jsonData: [String: Any]) {
        if let cellPhoneNumber = jsonData["CellPhoneNumber"] {
            self.cellPoneNumber = cellPhoneNumber as? String
        }
        
        if let idCard = jsonData["IDCard"] {
            self.idCard = idCard as? String
        }
        if let address = jsonData["Address"] {
            self.address = address as? String
        }
        if let iDCardValidEndDate = jsonData["IDCardValidEndDate"] {
            self.iDCardValidEndDate = iDCardValidEndDate as? String
        }
        if let iDCardValidBeginDate = jsonData["IDCardValidBeginDate"] {
            self.iDCardValidBeginDate = iDCardValidBeginDate as? String
        }
        
        
        if let username = jsonData["Name"] {
            self.username = username as? String
        }
        
        if let photoDict = jsonData["Photo"] as? [String: Any] {
            self.photoUrl = photoDict["Path"] as? String
        }
        
        self.avatarUrl = jsonData["Portrait"] as? String
        
        if let sex = jsonData["Sex"] as? Int {
            self.sex = Sex(rawValue: sex)
        }
        
        if let cityDic = jsonData["City"] as? [String: AnyObject] {
            if let cityname = cityDic["Name"] {
                self.city = cityname as? String
            }
            
            let cityModel = CityModel(rootDict: cityDic)
            self.cityModel = cityModel
        }
        if let provinceDic = jsonData["Province"] as? [String: AnyObject] {
            if let provincename = provinceDic["Name"] {
                self.province = provincename as? String
            }
            
            self.provinceModel = ProviceModel(rootDict: provinceDic)
        }
        
        if let arr = jsonData["IDCardSmartImageList"] as? [[String: Any]] {
            guard arr.count == 2 else {
               
                return
            }
            
            for dict in arr {
                if let photoName = dict["Name"] as? String {
                    if photoName.components(separatedBy: "positive").count > 1 {
                        self.positiveIdCardUrl = dict["Path"] as? String
                    }
                    if photoName.components(separatedBy: "reverse").count > 1 {
                        self.reverseIdCardUrl = dict["Path"] as? String
                    }
                }
            }
//            
//            let positiveDic = arr[0]
//            
//            self.positiveIdCardUrl = positiveDic["Path"] as? String
//            
//            let reverseDic = arr[1]
//            self.reverseIdCardUrl = reverseDic["Path"] as? String
        }
    }
    
    //获取民工资料
    class func getMigrantWorkInfo(completionHandler:@escaping ((WWValueResponse<UserInfoModel>) -> Void)) {
        guard let model = WWUser.sharedInstance.userModel, let accountId = model.accountId, let companyId = model.companyId,let userKey = model.userKey else {
            return
        }
        
        WWUser.sharedInstance.getToken(accountId, key: userKey) { (isSuccess) in
            if isSuccess {
                
                guard let httpHeader = mobile_cilent_headers() else {
                    return
                }
                
                let method = "MarTian.MigrantWorkerManage.Handler.AjaxConstructionTeamDetail.GetMigrantWorkInfo"
                let params = ["Method":method, "CompanyID":companyId, "AccountId": accountId]
                Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
                    if response.result.isSuccess {
                        if let value = response.result.value as? [String: AnyObject] {
                            let status = StatusStruct(rootJson: value)
                            if status.success {
                                if let dic = value["MGAuthentication"] as? [String: AnyObject] {
                                    
                                    let model = UserInfoModel.init(dic)
                                    completionHandler(WWValueResponse.init(value: model, success: true))
                                }
                            }
                            else {
                                completionHandler(WWValueResponse.init(success: false, message: status.statusString))
                            }
                            return
                        }
                        completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
                    }
                    else {
                        
                       
                        completionHandler(WWValueResponse.init(success: false, message: "网络访问错误"))
                    }
                }
            }
            else {
                completionHandler(WWValueResponse.init(success: false, message: "获取token失败，请重新登录"))
            }
        }
        

 
    }
}
